import type { Plugin } from 'vite'
import vue from '@vitejs/plugin-vue'
import Icons from 'unplugin-icons/vite'
import ViteDts from 'vite-plugin-dts'
import createAutoImport from './auto-import'
import createComponent from './components'
import createCompression from './compression'
import createSetupExtend from './setup-extend'
import createSvgIcon from './svg-icon'

interface ViteEnv {
  VITE_BUILD_COMPRESS?: string
}

function pushPlugin(plugin: Plugin | Plugin[], target: Plugin[]) {
  if (Array.isArray(plugin)) {
    target.push(...plugin)
  }
  else {
    target.push(plugin)
  }
}

export default function createVitePlugins(viteEnv: ViteEnv, isBuild = false): Plugin[] {
  const vitePlugins: Plugin[] = [
    vue(),
    ViteDts({
      include: ['src/**/*.vue'],
      outDir: 'src/types',
    }),
  ]

  pushPlugin(createAutoImport(), vitePlugins)
  pushPlugin(createComponent(), vitePlugins)
  pushPlugin(createSetupExtend(), vitePlugins)
  pushPlugin(createSvgIcon(isBuild), vitePlugins)

  if (isBuild) {
    pushPlugin(createCompression(viteEnv), vitePlugins)
  }

  Icons({
    autoInstall: true,
  })

  return vitePlugins
}
